'use strict';
const db = uniCloud.database();

function simpleDecrypt(encryptedPassword) {
	try {
		const decoded = Buffer.from(encryptedPassword, 'base64').toString();
		return decoded.split('').reverse().join('');
	} catch (error) {
		console.error('密码解密失败:', error);
		return null;
	}
}

exports.main = async (event, context) => {
	try {
		const {
			account,
			password
		} = event;

		console.log('收到登录请求:', {
			account
		});

		if (!account || !password) {
			return {
				code: 400,
				msg: '账户和密码不能为空'
			};
		}

		const accountRes = await db.collection('Accounts')
			.where({
				account: account
			})
			.get();

		console.log('查询结果:', accountRes.data.length);

		if (accountRes.data.length === 0) {
			return {
				code: 400,
				msg: '账户不存在'
			};
		}

		const accountData = accountRes.data[0];
		console.log('账户数据:', {
			user_id: accountData.user_id,
			hasPassword: !!accountData.password
		});

		const decryptedPassword = simpleDecrypt(accountData.password);

		console.log('密码验证:', {
			输入密码: password,
			存储密码: accountData.password,
			解密后密码: decryptedPassword,
			验证结果: decryptedPassword === password
		});

		if (decryptedPassword !== password) {
			return {
				code: 400,
				msg: '密码错误'
			};
		}

		const userRes = await db.collection('UserInfo')
			.doc(accountData.user_id)
			.get();

		if (userRes.data.length === 0) {
			return {
				code: 400,
				msg: '用户信息不存在'
			};
		}

		const userInfo = userRes.data[0];

		const currentTime = new Date();
		await db.collection('Accounts')
			.doc(accountData._id)
			.update({
				last_login_time: currentTime
			});

		const responseData = {
			token: 'user_token_' + Date.now() + '_' + accountData.user_id,
			userInfo: {
				id: accountData.user_id,
				account: accountData.account,
				name: userInfo.name || '',
				mobile: userInfo.mobile || '',
				email: userInfo.email || '',
				address: userInfo.address || '',
				intro: userInfo.intro || '',
				create_time: userInfo.create_time || ''
			}
		};

		console.log('登录成功，返回数据:', responseData);

		return {
			code: 200,
			msg: '登录成功',
			data: responseData
		};

	} catch (error) {
		console.error('登录失败：', error);
		console.error('错误详情：', error.message);
		return {
			code: 500,
			msg: '登录失败：' + error.message
		};
	}
};